# coding:utf-8
# 任务管理

import traceback, uuid
from ujson import dumps, loads
from sqlalchemy import and_, or_
import glog, gdb
from db_tables import *
import DATA_mission_enemy as DATA_me
from glb import BATTLE_RESULT_WIN


def _pack(d): return repr(d)
def _unpack(d): return eval(d)

# { role_id : { mission_id:[], .. }, .. }
data = {}


def init ():
    pass


"""
# 关卡静态数据因为填写方便的原因,格式和其他表有所不同,
# 需要初始化成程序容易读取的数据
def init_DATA ():
    for _, d in DATA_me.data.iteritems():
        mission_id = d['mission']
        if not mission_id in DATA_mission_enemy: DATA_mission_enemy[mission_id] = {}

        wave_id = d['wave']
        if not wave_id in DATA_mission_enemy[mission_id]: DATA_mission_enemy[mission_id][wave_id] = []

        # 添加一个数据
        DATA_mission_enemy[mission_id][wave_id].append((d['x'], d['y'], d['enemy_type']))
"""

# 完成关卡
def complete_mission (role_id, mission_id, stars):
    role_data = get(role_id)
    mission_data = role_data.get(mission_id, None) # old
    
    old_stars = mission_data[0] if mission_data else  0
    new_data = [max(old_stars, stars),]

    if not set(role_id, new_data):
        glog.error('complete_mission>set FAILED role_id:%s' % role_id)
        return False, "complete_mission>set FAILED"

    # 把奖励给玩家



    return True


# 获取关卡奖励
def get_mission_award (mission_id, stars):
    pass

# --------------------------------------------------
# 取得数据
def get (owner):
    dt = _get_owner_data(owner)
    return dt


# 存储数据
def set (owner, role_data):
    old_role_data = _get_owner_data(owner)

    data[owner] = role_data
    if not save_owner_data(owner):
        glog.error('mission_mgr>set FAILED, write db error, owner:%s' % owner)
        data[owner] = old_role_data
        return False
    return True 
    

def _get_owner_data (owner): 
    if owner not in data:
        cars = _load_db(owner)
        data[owner] = cars
    return data[owner]


def save_owner_data (owner):
    res = _save_db(owner, _get_owner_data(owner))
    if not res:
        glog.error('car_mgr>save_owner_data FAILED, owner:%s' % owner) 
    return res
    

# 从数据库中加载数据
def _load_db (owner):
    role_data = _unpack( db_get_data(owner) )
    return role_data


def _save_db (owner, role_data):
    return db_set_data( owner, _pack(role_data) )


# ------------------------------------------------------
def db_get_data (owner):
    ses = gdb.get_session()
    res = ses.query(DBMission).filter_by(id=owner).all() # only one
    if len(res) > 0:
        return res[0].data
    else:
        return "{}"

def db_set_data (owner, data):
    ses = gdb.get_session()
        
    res = ses.query(DBMission).filter_by(id=owner).all()
    if len(res) > 0:
        # update
        try:
            record = res[0]
            record.data = data
            ses.commit()
            return True
        except Exception, e:
            print traceback.format_exc()
            ses.rollback()
            return False
    else:
        # insert
        try:
            ses.add(DBMission(owner, data))
            ses.commit()
            return True
        except Exception, e:
            print traceback.format_exc()
            ses.rollback()
            return False


